from django.test import TestCase, Client
from django.urls import reverse
from .models import BlogCategory, BlogArticle
from users.models import BlogUser
import json


class BlogSubmitTestCase(TestCase):

    def setUp(self):
        self.client = Client()

    def test_blog_submit_valid_data(self):
        # 模拟用户已登录状态
        user = BlogUser.objects.create(username='testuser')
        category = BlogCategory.objects.create(name='Test Category')
        self.client.force_login(user)

        # 发布博文的有效数据
        data = {
            'title': 'Test Title',
            'content': 'Test Content',
            'category': 'Test Category'
        }
        response = self.client.post(reverse('blog_submit'), json.dumps(data), content_type='application/json')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(json.loads(response.content), {'message': 'successfully', 'code': 1})

        # 检查数据库中是否创建了新的博文
        self.assertTrue(BlogArticle.objects.filter(title='Test Title', content='Test Content', category=category,
                                                   username=user).exists())

    def test_blog_submit_missing_data(self):
        # 模拟用户已登录状态
        user = BlogUser.objects.create(username='testuser')
        self.client.force_login(user)

        # 发布博文的缺失数据
        data = {
            'content': 'Test Content',
            'category': 'Test Category'
        }
        response = self.client.post(reverse('blog_submit'), json.dumps(data), content_type='application/json')
        self.assertEqual(response.status_code, 400)
        self.assertEqual(json.loads(response.content), {'error': 'title is required'})

    def test_blog_submit_invalid_category(self):
        # 模拟用户已登录状态
        user = BlogUser.objects.create(username='testuser')
        self.client.force_login(user)

        # 发布博文的无效分类
        data = {
            'title': 'Test Title',
            'content': 'Test Content',
            'category': 'Nonexistent Category'
        }
        response = self.client.post(reverse('blog_submit'), json.dumps(data), content_type='application/json')
        self.assertEqual(response.status_code, 400)
        self.assertEqual(json.loads(response.content), {'error': 'Category does not exist'})
